package com.xiaoluyy.rpc.wrapper;

import com.xiaoluyy.rpc.config.ThriftRpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;
import org.springframework.util.CollectionUtils;


public class ThriftServerBootstrap implements SmartLifecycle {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThriftServerBootstrap.class);


    protected volatile boolean stopped = false;

    private ThriftRpcService thriftRpcService;

    public ThriftServerBootstrap(ThriftRpcService thriftRpcService) {
        this.thriftRpcService = thriftRpcService;
    }

    @Override
    public boolean isAutoStartup() {
        return true;
    }

    @Override
    public void stop(Runnable runnable) {
        stopped = false;
        thriftRpcService.shutdown();
    }

    @Override
    public void start() {
        if (CollectionUtils.isEmpty(thriftRpcService.getServiceConfigList())) {
            return;
        }
        LOGGER.info("Starting thrift servers");
        thriftRpcService.startup();
        stopped = false;
    }

    @Override
    public void stop() {
        stop(null);
    }

    @Override
    public boolean isRunning() {
        return this.stopped;
    }

    @Override
    public int getPhase() {
        return Integer.MAX_VALUE;
    }

}
